package com.talkyun.openx.client.codec;

import com.talkyun.utils.json.JSON;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Impl object <-> json  encode/decode
 * <p/>
 * Created by kevin on 3/22 0022.
 */
public class JsonCodec {

    public Object decode(Type type, String json) {
        // generic type
        if (type instanceof ParameterizedType) {
            ParameterizedType pt = ((ParameterizedType) type);
            Class<?> clazz = (Class<?>) pt.getRawType();
            // Generic List<E>
            if (clazz == List.class) {
                Class<?> targetClazz = (Class<?>) pt.getActualTypeArguments()[0];
                return JSON.toJavaList(json, targetClazz);
            }

            // other generic object
            return doDecode(pt, json);
        }

        return doDecode(type, json);
    }

    private Object doDecode(Type type, String json) {
        return json == null ? null : JSON.toJavaObject(json, type);
    }
}